package com.liveHere.www.servlet;

import com.liveHere.www.dao.*;
import com.liveHere.www.po.Admin;
import com.liveHere.www.po.Shop;
import com.liveHere.www.po.User;
import com.liveHere.www.util.JDBCUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.Scanner;

/**
 * @author Mo312
 */
public class AdminServlet {
    private final UserDao userDao = new UserDaoImpl();
    private final ShopDao shopDao = new ShopDaoImpl();
    private final AdminDao adminDao = new AdminDaoImpl();

    public void start() {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println();
            System.out.println("-------------------LiveHere Admin----------------------");
            System.out.println("-------------------------------------------------------");
            System.out.println("1. 登录");
            System.out.println("2. 退出");
            System.out.print("\n请输入你的选择：");
            int choice = scanner.nextInt();
            scanner.nextLine(); // 清除缓冲区

            switch (choice) {
                case 1:
                    login();
                    break;
                case 2:
                    System.out.println("退出系统");
                    return;
                default:
                    System.out.println("无效输入");
            }
        }
    }

    //管理员登录
    public void login() {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.print("\n");
            System.out.print("请输入管理员用户名: ");
            String adminName = scanner.nextLine();
            System.out.print("请输入管理员密码: ");
            String password = scanner.nextLine();

            try {
                Admin admin = adminDao.login(adminName, password);
                if (admin != null) {
                    System.out.println("登录成功");
                    adminMenu();
                } else {
                    System.out.println("用户名或密码错误");
                }
            } catch (SQLException e) {
                System.out.println("登录失败: " + e.getMessage());
                e.printStackTrace();
            }
        }
    }

    public void adminMenu() {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.print("\n");
            System.out.println("1. 查看商家信息");
            System.out.println("2. 审核店铺入驻申请");
            System.out.println("3. 封禁店铺");
            System.out.println("4. 审核租户充值信息");
            System.out.println("5. 退出");
            System.out.print("请输入你的选择：");
            int choice = scanner.nextInt();
            scanner.nextLine(); // 清除缓冲区

            switch (choice) {
                case 1:
                    viewAllShops();
                    break;
                case 2:
                    checkShopApplications();
                    break;
                case 3:
                    banShop();
                    break;
                case 4:
                    checkUserRecharges();
                    break;
                case 5:
                    System.out.println("返回主菜单");
                    return;
                default:
                    System.out.println("无效输入");
            }
        }
    }

    //查看所有店铺信息
    public void viewAllShops() {
        try {
            System.out.println();
            ArrayList<Shop> shops = shopDao.getAllShops();
            if (shops.isEmpty()) {
                System.out.println("\n无店铺信息");
            } else {
                System.out.println("\n店铺列表：");
                for (Shop shop : shops) {
                    System.out.println("店铺ID: " + shop.getShopId());
                    System.out.println("店铺名称: " + shop.getShopName());
                    System.out.println("地址: " + shop.getShopAddress());
                    System.out.println("联系方式: " + shop.getShopContact());
                    System.out.println("关键词: " + shop.getKeywords());
                    System.out.println("营业状态: " + shop.getStatus());
                    System.out.println("入驻申请状态: " + shop.getApplyStatus());
                    System.out.println("申请时间: " + shop.getDate());
                    System.out.println("-------------------------------");
                }
            }
        } catch (Exception e) {
            System.out.println("查询店铺失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    //审核店铺入驻申请
    public void checkShopApplications() {
        Scanner scanner = new Scanner(System.in);
        try {
            ArrayList<Shop> shops = shopDao.getPendingShops();
            System.out.print("\n");
            if (shops.isEmpty()) {
                System.out.println("暂无待审核的店铺申请");
            } else {
                System.out.println("待审核的店铺列表：");
                for (Shop shop : shops) {
                    System.out.println("店铺ID: " + shop.getShopId());
                    System.out.println("店铺名称: " + shop.getShopName());
                    System.out.println("地址: " + shop.getShopAddress());
                    System.out.println("联系方式: " + shop.getShopContact());
                    System.out.println("关键词: " + shop.getKeywords());
                    System.out.println("营业状态: " + shop.getStatus());
                    System.out.println("申请时间: " + shop.getDate());
                    System.out.println("-------------------------------");
                }

                System.out.print("请输入要审核的店铺ID（输入0返回）：");
                int shopId = scanner.nextInt();
                scanner.nextLine(); // 清除缓冲区

                if (shopId == 0) {
                    return; // 返回主菜单
                }

                System.out.print("请输入审核结果（approve/reject）：");
                String result = scanner.nextLine();

                if ("approve".equalsIgnoreCase(result)) {
                    shopDao.approveShop(shopId);
                    System.out.println("店铺审核通过");
                } else if ("reject".equalsIgnoreCase(result)) {
                    shopDao.rejectShop(shopId);
                    System.out.println("店铺审核拒绝");
                } else {
                    System.out.println("无效的审核结果");
                }
            }
        } catch (SQLException e) {
            System.out.println("审核店铺失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    //封禁店铺
    public void banShop() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("\n");
        try {
            System.out.print("请输入要封禁的店铺ID：");
            int shopId = scanner.nextInt();
            scanner.nextLine(); // 清除缓冲区

            shopDao.banShop(shopId);
            System.out.println("店铺已封禁");
        } catch (SQLException e) {
            System.out.println("封禁店铺失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    //审核租户充值信息
    public void checkUserRecharges() {
        Scanner scanner = new Scanner(System.in);
        Connection conn = null;
        try {
            // 获取连接并开启事务
            conn = JDBCUtils.getConnection();
            conn.setAutoCommit(false);

            ArrayList<User> users = userDao.getPendingRecharges();
            System.out.print("\n");
            if (users.isEmpty()) {
                System.out.println("暂无待审核的用户充值");
            } else {
                System.out.println("待审核的用户充值列表：");
                for (User user : users) {
                    System.out.println("用户ID: " + user.getUserid());
                    System.out.println("用户名: " + user.getUsername());
                    System.out.println("充值金额: " + user.getAmountToBeRecharged());
                    System.out.println("-------------------------------");
                }

                System.out.print("请输入要审核的用户ID（输入0返回）：");
                int userId = scanner.nextInt();
                scanner.nextLine(); // 清除缓冲区

                if (userId == 0) {
                    return; // 返回主菜单
                }

                User selectedUser = null;
                for (User user : users) {
                    if (user.getUserid() == userId) {
                        selectedUser = user;
                    }
                }

                if (selectedUser == null) {
                    System.out.println("未找到用户ID对应的充值请求");
                    return;
                }

                System.out.print("请输入审核结果（approve/reject）：");
                String result = scanner.nextLine();

                if ("approve".equalsIgnoreCase(result)) {
                    // 审核通过
                    userDao.approveRecharge(userId);
                    userDao.updateBalance(userId, selectedUser.getAmountToBeRecharged());
                    System.out.println("用户充值审核通过");
                    // 提交事务
                    conn.commit();
                } else if ("reject".equalsIgnoreCase(result)) {
                    // 审核拒绝
                    userDao.rejectRecharge(userId);
                    System.out.println("用户充值审核拒绝");
                    // 提交事务
                    conn.commit();
                } else {
                    System.out.println("无效的审核结果");
                    // 回滚事务
                    conn.rollback();
                }
            }
        } catch (Exception e) {
            // 发生异常时回滚事务
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            System.out.println("审核用户充值失败: " + e.getMessage());
            e.printStackTrace();
        } finally {
            // 关闭连接
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
